package chain_apply

import (
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/repository/mongodb/chain_apply"
	"chain_bridge_service/internal/repository/mongodb/chain_token"
	"github.com/pkg/errors"
	"time"
)

type RequestData struct {
	ChainConfigId0 string
	ChainConfigId1 string
	TokenId0       string
	TokenId1       string
	TxHash         string
	From           string
	To             string
	UserId         string
	Amount0        string
	Amount1        string
}

func (s *service) Create(ctx core.Context, keyData *RequestData) error {
	number, err := chain_apply.GetInfoByTxHash(s.db.GetDb(), keyData.TxHash)
	if err != nil {
		return err
	}
	if number != 0 {
		return errors.New("txHash重复")
	}

	_, err = chain_token.GetInfoById(s.db.GetDb(), keyData.TokenId0)
	if err != nil {
		return errors.New("未查到卖出token信息")
	}
	_, err = chain_token.GetInfoById(s.db.GetDb(), keyData.TokenId1)
	if err != nil {
		return errors.New("未查到买入token信息")
	}

	model := new(chain_apply.ChainApply)
	model.ChainConfigId0 = keyData.ChainConfigId0
	model.ChainConfigId1 = keyData.ChainConfigId1
	model.TokenId0 = keyData.TokenId0
	model.TokenId1 = keyData.TokenId1
	model.TxHash = keyData.TxHash
	model.From = keyData.From
	model.To = keyData.To
	model.UserId = keyData.UserId
	model.Status = "0"
	model.Amount0 = keyData.Amount0
	model.Amount1 = keyData.Amount1
	model.TimeStamp = time.Now().Unix()
	err = model.Create(s.db.GetDb())
	return err
}
